<template>
	<view class="pages">
		<uni-segmented-control v-if="disabled" :current="current" :values="items" style-type="text" active-color="#2D82F6" @clickItem="onClickItem" style="margin-bottom: 20px;"/>
		<view v-if="current === 0">
			<uni-forms class="dialog-content" ref="valiForm" :modelValue="formData" :rules="rules">
        <uni-forms-item label="点位" name="devbm" required>
          <uni-easyinput type="text" style="display: none;" v-model="formData.devbm"/>
          <uni-data-picker v-if="!disabled" @change="onchangeType" v-model="formData.devbm"  popup-title="请选择点位" :localdata="pointOptions" :map="{text:'devname',value:'devbm'}"></uni-data-picker>
          <uni-easyinput v-else :disabled="disabled" type="text" :value="formData.devname"/>
        </uni-forms-item>
        <uni-forms-item label="位置描述">
          <uni-easyinput :disabled="disabled" type="text" v-model="formData.locationDesc" maxlength="10" placeholder="请输入位置描述"/>
        </uni-forms-item>
        <template v-for="(item, index) in indexList">
            <uni-forms-item :label="item.indexName + (item.indexUnit ? ('(' + item.indexUnit + ')') : '')">
              <uni-easyinput :disabled="disabled" type="number"  v-model="item.indexValue" :min="0" placeholder="请输入指标值" />
            </uni-forms-item>
        </template>
				<uni-forms-item label="备注">
					<uni-easyinput :disabled="disabled" type="textarea" v-model="formData.gatherNote" maxlength="50" placeholder="请输入备注"/>
				</uni-forms-item>
				<uni-forms-item label="上传图片" v-if="!disabled">
					<uni-file-picker limit="3" ref="files" :auto-upload="false"></uni-file-picker>
				</uni-forms-item>
				<uni-forms-item label="图片"  v-if="disabled">
					<uni-file-picker :readonly="true"  :value="formData.pics|imagesFormat" limit="2" ref="files"></uni-file-picker>
				</uni-forms-item>
				<button type="primary" :hidden="disabled" @click="submit('valiForm')">提交</button>
			</uni-forms>
		</view>
		<view v-if="current === 1">
			<Liststeps v-for="(item, index) in stepList2" :activity="item.done" :key="index" :index="index">
				<text slot="date" v-if="index == 0" style="color: #2D82F6;" >{{ item.date }}</text>
				<text slot="date" v-else >{{ item.date }}</text>
				<view slot="content">
					<view class="info_item" v-for="(info, index) in item.infoList" :key="index">
						<view class="label">{{ info.label }}：</view>
						<view :class="info.alarmRecord ? 'value alarm' : 'value'"> {{ info.value }}{{ info.unit || '' }}</view>
					</view>
				</view>
				<view slot="content" style="margin-bottom: 20px;" v-if="item.pics.length > 0">
					<view class="info_item">
						<view class="label">附件：</view>
						<view class="value">
							<uni-file-picker :readonly="true"  :value="item.pics|imagesFormat" limit="2" ref="files"></uni-file-picker>
						</view>
					</view>
				</view>
			</Liststeps>
			<cell class="loading-more" v-if="stepList2.length == 0">
				<image style="width:450rpx;height:450rpx;margin-top: 300rpx;margin-left: 80px;" src="../../../static/icon/noData.png"></image>
			</cell>
		</view>
    <view v-if="current === 2">
      <Liststeps v-for="(item, index) in stepList" :activity="item.done" :key="index" :index="index">
        <text slot="date" v-if="index == 0" style="color: #2D82F6;" >{{ item.date }}</text>
        <text slot="date" v-else >{{ item.date }}</text>
        <view slot="content">
          <view class="info_item" v-for="(info, index) in item.infoList" :key="index">
            <view class="label">{{ info.label }}：</view>
            <view class="value"> {{ info.value }}{{ info.unit || '' }}</view>
          </view>
        </view>
        <view slot="content" style="margin-bottom: 20px;" v-if="item.pics.length > 0">
          <view class="info_item">
            <view class="label">附件：</view>
            <view class="value">
              <uni-file-picker :readonly="true"  :value="item.pics|imagesFormat" limit="2" ref="files"></uni-file-picker>
            </view>
          </view>
        </view>
      </Liststeps>
			<cell class="loading-more" v-if="stepList.length == 0">
				<image style="width:450rpx;height:450rpx;margin-top: 300rpx;margin-left: 80px;" src="../../../static/icon/noData.png"></image>
			</cell>
    </view>
	</view>
</template>
<script>
  import { mapGetters } from 'vuex'
	import baseUrl from '../../../config/baseUrl.js'
	import Liststeps from '../../../components/lwp-step/lwp-step.vue'
  import { getTargets,getHandleRecordList } from '../../../api/alarm'
  import { add,queryByDevbm } from '../../../api/fishDegrade'
  import { list as getDeviceList } from '../../../api/device'
	let that = null
	export default {
		components: { Liststeps },
    computed: { ...mapGetters({ userInfo: 'userInfo' }) },
		data() {
			return {
				current: 0,
				disabled:false,
        address:'',
				items:['报警详情','报警记录','处置记录'],
				stepList:[],
				stepList2:[],
        indexList: [],//所有指标
				pointOptions:[],
				formData:{ pics:[],indexContent:[] },
				rules: {
          devbm: {
						rules: [{
								required: true,
								errorMessage: '请选择点位',
							}
						]
					},
				}
			}
		},
		created() {
		},
		onLoad(options) {
      that = this
			if(options.id != null){
				// 查看
				uni.setNavigationBarTitle({ title:'渔业种群退化详情' })
				this.disabled = true
				uni.getStorage({
				    key:'detail',
				    success:res=>{
						  this.formData = res.data
              this.formData.pics = []
              let pics = JSON.parse(res.data.gatherPics)
              if(pics != null){
              				  pics.forEach(item=>{
              				    this.formData.pics.push({
              				      filePath:item.url,
              				      imgName:item.name
              				    })
              				  })
              }
              this.indexList = JSON.parse(res.data.indexContent)
					}
				})
			}else{
        getTargets({ pageNum: 1, pageSize: 999999, indexType:6 }).then(response => {
          this.indexList = response.rows
        })
      }
      getDeviceList({ pageNum: 1,pageSize: 999,devtypebm:'FISH_DEGENERATE_MONITOR' }).then(res => {
				this.pointOptions = res.rows
			})
		},	
		methods: {
			onClickItem(e) {
				if (this.current !== e.currentIndex) {
					this.current = e.currentIndex
				}
        if(e.currentIndex == 1) {
          queryByDevbm({ devbm:this.formData.devbm }).then(res => {
						this.stepList2 = []
            res.data.forEach(item => {
              let pics = []
              let html = []
              if(item.gatherPics != null && item.gatherPics != '') {
                let json = JSON.parse(item.gatherPics)
                json.forEach(file => {
                  pics.push({ filePath: file.url, fileName: file.name })
                })
              }
              if(item.indexContent != null && item.indexContent != '') {
                let json2 = JSON.parse(item.indexContent)
                json2.forEach(content => {
                  html.push({
                    label: content.indexName,
                    value: content.indexValue,
                    unit: content.indexUnit,
                    alarmRecord: content.alarmRecord,
                  })
                })
              }
              this.stepList2.push({
                date : item.gatherTime.substring(5,16),
                businessId : item.replyId,
                done : false,
                infoList:html,
                pics:pics
              })
              this.stepList2[0].done = true
            })
          })
        } else if(e.currentIndex == 2){
          getHandleRecordList({ pageNum: 1,pageSize: 999,businessId:this.formData.id }).then(res => {
						this.stepList = []
            res.rows.forEach(item => {
              let pics = []
              if(item.gatherPics != null && item.gatherPics != '') {
                let json = JSON.parse(item.gatherPics)
                json.forEach(file => {
                  pics.push({ filePath: file.url, fileName: file.name })
                })
              }
              this.stepList.push({
                date : item.handleTime.substring(5,16),
                businessId : item.replyId,
                done : false,
                infoList:[
                  {
                    label: '描述',
                    value: item.handleContent
                  },
                  {
                    label: '操作人',
                    value: item.handleUserName
                  }
                ],
                pics:pics
              })
              this.stepList[0].done = true
            })
          })
        }
			},
      onchangeType(e) {
			  const select = e.detail.value[0]
			  this.formData.devname = select.text
			},
			uploadPic(){
				let pics = []
				let token = this.userInfo.token
				let length = this.$refs.files.files.length
				let count = 0 
				return new Promise((resolve, reject)=>{
					this.$refs.files.files.forEach(function(item, index) {
						let n = uni.uploadFile({
						    url: baseUrl.baseUrl +'/public/uploadAttachmentFile',
							  header: { 'token': token },
						    filePath: item.url,
						    name: 'file',
						    success: uploadFileRes => {
								let json = JSON.parse(uploadFileRes.data)
								pics.push({
                  name:item.name,
                  url:json.data
                })
								count++
								if(count == length){
									resolve(pics)
								}
						    }
						})
					})
					
				})
			},
			async submit() {
				if(this.$refs.files.files.length > 0){
					let roadDiseaseSporPics = await this.uploadPic()
					this.formData.gatherPics = JSON.stringify(roadDiseaseSporPics)
				}
				this.$refs.valiForm.validate().then(res=>{
          //指标采集值格式化成字符串
          if(that.indexList && that.indexList.length > 0){
            that.indexList.forEach(function(item){//删除告警记录属性
              if(item.alarmRecord){
                delete item.alarmRecord
              }
            })
            that.formData.indexContent = JSON.stringify(that.indexList)
          }
					add(this.formData).then(res => {
						uni.showToast({
							title: '保存成功',
							duration: 1000
						})
						uni.navigateTo({ url:'./index' })
					})
				}).catch(err =>{
					console.log('表单错误信息：', err)
				})
			}
		}
	}
</script>


<style lang="less">
	.statausBtton{
		color: #2D82F6;
		margin-bottom:10px;
		margin-top:-10px;
		margin-right: -30px;
		font-size: 25rpx;
		background-color: transparent;
	}
	.grid-item-box {
		flex: 1;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 15px 0;
	}
	 
	.list {
		margin-bottom: 30rpx;
		background-color: #f9f9f9;
	}
	
	.diseaseList{
		font-size: 36rpx;
	}
	
	.diseaseList-header{
		color: #666666;
		flex-direction: row;
	}
	
	.info_item {
	  font-size: 28rpx;
	  font-weight: 400;
	  color: #949596;
	  display: flex;
	  .value {
		flex: 1;
		margin-left: 0rpx;
		font-size: 30rpx;
		font-weight: 400;
		color: #4a4d50;
	  }
    .alarm{
      color: red;
    }
	}
</style>
<style lang="scss">
	.pages {
		background-color: #FFFFFF;
	}
	.dialog-content{
		background-color: #fff;
		padding:10rpx 50rpx 30rpx;
		border-radius: 10rpx;
		font-size: 24rpx;
	}
</style>